import { Injectable } from '@nestjs/common';
import { CreateZhimaDto } from './dto/create-zhima.dto';
import { UpdateZhimaDto } from './dto/update-zhima.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Zhima } from './entities/zhima.entity';
import { Repository } from 'typeorm';
import { formatError, formatPage, formatSuccess } from 'src/util';

@Injectable()
export class ZhimaService {
  constructor(
    @InjectRepository(Zhima)
    private readonly zhimaRepository: Repository<Zhima>,
  ) {}

  // 查询
  async findAll(params) {
    const pageNum = params.pageNum || 1;
    const pageSize = params.pageSize || 10;
    const where: any = {};
    // 获取总条数
    const total = await this.zhimaRepository.count({ where });
    // 查第几页的数据
    let list = [];
    if (total > 0) {
      list = await this.zhimaRepository.find({
        skip: (pageNum - 1) * pageSize,
        take: pageSize,
        where,
        order: { create_time: 'DESC' },
      });
    }
    return formatPage({ pageNum, pageSize, total, list });
  }

  // 新增
  async create(createZhimaDto: CreateZhimaDto) {
    const userinfo = await this.findOne(createZhimaDto.name);
    if (userinfo) return formatError({ msg: '账户名已存在' });
    const data = await this.zhimaRepository.save({
      ...createZhimaDto,
    });
    return formatSuccess('新增成功');
  }

  // 查询单个
  async findOne(name: string) {
    const data = await this.zhimaRepository.findOneBy({ name });
    return data;
  }

  // 查询单个-id
  async findOneById(id: number) {
    const data = await this.zhimaRepository.findOneBy({ id });
    return data;
  }

  // 修改
  async edit(createZhimaDto: CreateZhimaDto) {
    const data: any = await this.zhimaRepository.update({ id: createZhimaDto.id }, createZhimaDto);
    if (data.affected > 0) {
      return formatSuccess('成功');
    } else {
      return formatError({ msg: '失败' });
    }
  }

  remove(id: number) {
    return `This action removes a #${id} zhima`;
  }
}
